package cn.hzking.gjmall.activitys.my;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.adpters.address.AddressAdapter;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.address.AddressSimpleBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseEntity;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.net.base.GjCustomStateViewObserver;
import cn.hzking.gjmall.utils.ListUtils;
import cn.hzking.gjmall.utils.UIUtils;
import cn.hzking.gjmall.view.ObservableScrollView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class AddressListActivity extends ColorStatuBarActivity implements AddressAdapter.AddressDefault{
    public static final int RESULT_DATA=100;
    @Bind(R.id.rv) RecyclerView recyclerview;
    @Bind(R.id.rl_back) RelativeLayout backRl;
    @Bind(R.id.rl_add) RelativeLayout addRl;
    @Bind(R.id.sl) StateLayout sl;
    @Bind(R.id.refresh) SwipeRefreshLayout refresh;
    @Bind(R.id.sv) ObservableScrollView sv;
    AddressAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_address_list);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        backRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        addRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mContext, AddAdressActivity.class);
                startActivityForResult(intent,RESULT_DATA);
            }
        });
        adapter=new AddressAdapter(R.layout.item_address,null);
        adapter.setAddressDefault(this);
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        recyclerview.setAdapter(adapter);
        setData(true,false,true);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                setData(false,true,false);
            }
        });
        sv.setScrollViewListener(new ObservableScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                if(y<=0){
                    refresh.setEnabled(true);
                }else {
                    refresh.setEnabled(false);
                }
            }
        });
    }

    private void setData(boolean isFirst,boolean isRefresh,boolean showDialog) {
        RetrofitFactory.getInstant().API()
                .getAddressList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new GjCustomStateViewObserver<AddressSimpleBean>(this,sl,refresh,isFirst,isRefresh,showDialog,true,null,null,null) {
                    @Override
                    protected void onBusinessSuccess(AddressSimpleBean addressSimpleBean) throws Exception {
                        if(addressSimpleBean!=null){
                            adapter.setNewData(addressSimpleBean.getData().getDeliveryAddressesList());
                        }
                        if(adapter.getData().size()>0){
                            addRl.setVisibility(View.VISIBLE);
                        }else {
                            View view = View.inflate(AddressListActivity.this,R.layout.layout_addresslist_empty,null);
                            RelativeLayout newRl=view.findViewById(R.id.rl_new);
                            newRl.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent=new Intent(mContext, AddAdressActivity.class);
                                    startActivity(intent);
                                }
                            });
                            sl.showCustomView(view);
                        }
                    }

                    @Override
                    protected void onChildFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        addRl.setVisibility(View.GONE);
                    }

                    @Override
                    protected void onBusinessFail(AddressSimpleBean addressSimpleBean) {
                        super.onBusinessFail(addressSimpleBean);
                        addRl.setVisibility(View.GONE);
                        UIUtils.showToastShort(AddressListActivity.this,addressSimpleBean.getErrorMsg());
                    }
                    /* @Override
                    protected void onSuccees(AddressSimpleBean addressSimpleBean) throws Exception {
                        if(addressSimpleBean!=null){
                            if(!ListUtils.isEmpty(addressSimpleBean.getData().getDeliveryAddressesList())){
                                adapter.setNewData(addressSimpleBean.getData().getDeliveryAddressesList());
                            }
                        }
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        if(isNetWorkError){
                            UIUtils.showToastShort(AddressListActivity.this,getResources().getString(R.string.net_error));
                        }else {
                            UIUtils.showToastShort(AddressListActivity.this,"服务器错误");
                        }
                    }

                    @Override
                    protected void onCodeError(AddressSimpleBean addressSimpleBean) throws Exception {
                        super.onCodeError(addressSimpleBean);
                        UIUtils.showToastShort(AddressListActivity.this,addressSimpleBean.getErrorMsg());
                    }*/
                });
    }

    @Override
    public void setdefault(int addressId) {
       //先调用设置默认接口，再调用刷新数据接口
        RetrofitFactory.getInstant().API()
                .setDefaultaddress(addressId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseEntity>(this,true) {

                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        setData(false,false,false);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        if(isNetWorkError){
                            UIUtils.showToastShort(AddressListActivity.this,getResources().getString(R.string.net_error));
                        }else {
                            UIUtils.showToastShort(AddressListActivity.this,"服务器错误");
                        }
                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(AddressListActivity.this,baseEntity.getErrorMsg());
                    }
                });
    }

    @Override
    public void del(final int addressId) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_order, null);// 得到加载view
        TextView titleTv=view.findViewById(R.id.tv_title);
        TextView cancelTv=view.findViewById(R.id.tv_cancel);
        TextView sureTv=view.findViewById(R.id.tv_sure);
        titleTv.setText("确定删除该地址?");

        final Dialog orderDialog = new Dialog(this, R.style.mydialog);// 创建自定义样式dialog
        orderDialog.setCanceledOnTouchOutside(false);
        orderDialog.setCancelable(false);
        orderDialog.setContentView(view);
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderDialog.dismiss();
            }
        });
        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderDialog.dismiss();
                delAddress(addressId);
            }
        });
        orderDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_DATA) {
            setData(true,false,true);
        }
    }

    private void delAddress(int addressId) {
        RetrofitFactory.getInstant().API()
                .delAddress(addressId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseEntity>(this,true) {

                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        setData(false,false,false);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        if(isNetWorkError){
                            UIUtils.showToastShort(AddressListActivity.this,getResources().getString(R.string.net_error));
                        }else {
                            UIUtils.showToastShort(AddressListActivity.this,"服务器错误");
                        }
                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(AddressListActivity.this,baseEntity.getErrorMsg());
                    }
                });
    }
}
